#include "libpear_option.h"
#include <getopt.h>

#ifdef __cplusplus
extern "C" {
#endif

void pear_getopt(int argc, char **argv, libpear_option_info_t *info, int info_count)
{
	// 
	//
	char char_params[512];
	int  char_params_index = 0;

	struct option string_params[256];
	int  string_params_index = 0;
	int  longindex;				// unused, used by getopt_long only

	//
	//
	int info_need_ret[256];
	int info_need_ret_index = 0;

	// 
	//
	int ret;
	int i;

	for (i = 0; i < info_count; i++) {
		switch (info[i].str[1]) {
			case '\0':
				char_params[char_params_index++] = info[i].str[0];
				info_need_ret[info_need_ret_index++] = info[i].str[0];
				break;

			case ':':
				char_params[char_params_index++] = info[i].str[0];
				char_params[char_params_index++] = info[i].str[1];
				info_need_ret[info_need_ret_index++] = info[i].str[0];
				break;

			default:
				string_params[string_params_index].name = info[i].str;
				string_params[string_params_index].has_arg = required_argument;
				string_params[string_params_index].flag = 0;
				string_params[string_params_index].val = 256 + i;	// 256 skip short option ascii
				string_params_index++;
				info_need_ret[info_need_ret_index++] = 256 + i;		// 256 skip short option ascii
				break;
		}
	}
	char_params[char_params_index] = 0;
	string_params[string_params_index].name = 0;
	string_params[string_params_index].has_arg = 0;
	string_params[string_params_index].flag = 0;
	string_params[string_params_index].val = 0;

	//
	//
	while ((ret = getopt_long(argc, argv, char_params, string_params, &longindex)) != -1) {

		for (i = 0; i < info_count; i++) {
			if (ret == info_need_ret[i] && info[i].func) {
				info[i].func(optarg); 
			}
		}
	}
}


#ifdef __cplusplus
} // extern "C"
#endif


